import React, { useState, useRef, useEffect } from 'react'
import { useDispatch } from 'react-redux'
import styles from './index.module.scss'
import { message, Card, Breadcrumb, Form, Input, Upload, Button, Space, Radio } from 'antd'
import { Link } from 'react-router-dom'
import MyChannels from '@/components/MyChannels'
import ReactQuill from 'react-quill'
import { PlusOutlined } from '@ant-design/icons';
import { saveArticle, getArticle, editArticle } from '@/store/actions/article'
import 'react-quill/dist/quill.snow.css'
import { useHistory } from 'react-router-dom'
import { useParams } from 'react-router-dom'
// 支持的文件的类型
const FILETYPE = ['image/jpg','image/gif', 'image/jpeg', 'image/png']
export default function Publish() {
  console.log('Publish..................')
  // 可以用来做编辑
  // const id = 
  const dispatch = useDispatch()
  const history = useHistory()
  // history.location.search => id=xxxxxx&a=2
  // const obj = new URLSearchParams(history.location.search) 
  // const id = obj.get("id")
  const { id } = useParams()
  useEffect(()=>{
    if(id){
      dispatch(getArticle(id)).then(res => {
        console.log('文章详情', res)
        const { title, content, channel_id, cover:{ type, images } } = res.data
        formRef.current.setFieldsValue({
          type,
          title,
          content,
          channel_id
        })

        setType(type)
        const fList = images.map(img =>{
          return {
            url: img
          }
        })
        setFileList(fList)
        fileRef.current = fList
      })
    }
  }, [id, dispatch])

  const formRef = useRef(null)
  // 图片的数量
  const [type, setType] = useState(1)
  const onTypeChange = (e) => {
    console.log(e)
    const count = e.target.value
    setType(count)

    // 从fileRef中取出图片，展示
    setFileList(fileRef.current.slice(0, count))
  }
  const [fileList, setFileList] = useState([
    // {
    //   url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png'
    // }
  ])

  // 保存所有的图片
  const fileRef = useRef(fileList)

  function beforeUpload(file) {
    const isJpgOrPng = FILETYPE.includes(file.type)
    if (!isJpgOrPng) {
      message.error('You can only upload JPG/PNG file!');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error('Image must smaller than 2MB!');
    }
    return isJpgOrPng && isLt2M;
  }
  const onChange = ({file, fileList}) => {
    console.log({file, fileList})
    if(FILETYPE.includes(file.type)){
      setFileList(fileList)
      // 更新fileRef
      fileRef.current = fileList
    }

    formRef.current.validateFields(['type'])
  }

  const addArticle = async (values, isDraft) => {
    console.log(fileList)
    // 1. 根据接口文档的要求，组装数据
    // const images = fileList.map(obj => {
    //   if(obj.url){
    //     return obj.url
    //   } else {
    //     return obj.response.data.url
    //   }
    // })
    // const images = fileList.map(obj => obj.url ? obj.url : obj.response.data.url)
    const images = fileList.map(obj => obj.url || obj.response.data.url)

    const data = {
      title: values.title,
      content: values.content,
      cover: {
        type,
        images
      },
      channel_id: values.channel_id 
    }
    console.log(data)
    // 2. dispatch
    id ? await dispatch(editArticle({...data,id }, isDraft))
    : await dispatch(saveArticle(data, isDraft))

    message.success((id ? '修改' : '添加') + '成功')
    // if(id){
    //   await dispatch(editArticle({...data,id }, isDraft))
    //   message.success('修改成功')
    // } else {
    //   await dispatch(saveArticle(data, isDraft))
    //   message.success('添加成功')
    // }
    history.push('/home/article')
  }

  // 添加|修改文章
  const onFinish = (values) => {
    addArticle(values, false)
  }

  // 添加草稿
  const addDraft = () => {
    formRef.current.validateFields().then(values => {
      addArticle(values, true)
    }).catch(()=>{

    })
  }

  return (
    <div className={styles.root}>
      <Card
        title={
          <Breadcrumb separator=">">
            <Breadcrumb.Item>
              <Link to="/home">首页</Link>
            </Breadcrumb.Item>
            <Breadcrumb.Item>{id ? '编辑' : '发布'}文章</Breadcrumb.Item>
          </Breadcrumb>
        }
      >
        <Form
          ref={formRef}
          labelCol={{ span: 4 }}
          onFinish={onFinish}
          wrapperCol={{ span: 20 }} size="large"
          initialValues={{content:'', type: 1}} >
          <Form.Item label="标题"
          name="title"
          rules={[
            {
              required: true,
              message: '标题不能为空'
            }
          ]}>
            <Input
              placeholder="请输入文章的标题"
              style={{ width: 400 }}
            ></Input>
          </Form.Item>
          <Form.Item label="频道"
            name="channel_id"
            rules={[
              {
                required: true,
                message: '频道不能为空'
              }
            ]}>
            <MyChannels/>
          </Form.Item>
          <Form.Item label="封面"
            name="type"
            rules={[
              {
                validator(_, value) {
                  if (fileList.length !== value) {
                    return Promise.reject(new Error(`请上传${value}张图片`))
                  } else {
                    return Promise.resolve()
                  }
                }
              }
            ]}
            >
            <Radio.Group value={type} onChange={onTypeChange}>
              <Radio value={1}>单图</Radio>
              <Radio value={3}>三图</Radio>
              <Radio value={0}>无图</Radio>
            </Radio.Group>
					</Form.Item>
          <Form.Item wrapperCol={{ offset: 4, span: 20 }}>
            {/* 
              action: 上传的地址
              name: 上传的文件的名字 默认file
              fileList: 显示控制上传的图片, 做回填
              Upload组件中没有嵌入内容，则整个组件不可见
              */}
            <Upload listType="picture-card" fileList={fileList}
              action="http://toutiao.itheima.net/v1_0/upload"
              name="image"
              beforeUpload={beforeUpload}
              onChange={onChange}
              maxCount={type}
            >
              {/* 如果fileList的长度 < type, 显示 + */}
              { fileList.length < type ? <PlusOutlined /> : null}
            </Upload>
          </Form.Item>

          <Form.Item label="内容"
            name="content"
            rules={[
              {
                required: true,
                message: '内容不能为空'
              }
            ]}>
            <ReactQuill></ReactQuill>
          </Form.Item>

          <Form.Item wrapperCol={{ offset: 4, span: 20 }}>
            <Space>
              <Button type="primary" htmlType='submit'>发布文章</Button>
              <Button onClick={addDraft}>存入草稿</Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>
    </div>
  )
}
